define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        category: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'product/category' + location.search,
                    add_url: 'product/categoryadd',
                    edit_url: 'product/categoryedit',
                    del_url: 'product/categorydel',
                    multi_url: 'product/categorydel',
                    table: 'product_category',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'parent_id,sort',
                sortOrder: 'asc',
                pagination: false,  // 树形表格不使用分页
                search: false,
                commonSearch: false,

                onLoadSuccess: function(data) {
                    console.log('Category data loaded:', data);
                    // 手动添加树形图标和处理展开/收缩
                    setTimeout(function() {
                        table.find('tbody tr').each(function(index) {
                            var $row = $(this);
                            var rowData = data.rows[index];
                            if (rowData && rowData._hasChildren) {
                                var $nameCell = $row.find('td').eq(2); // 分类名称列
                                if ($nameCell.find('.tree-toggle').length === 0) {
                                    var $icon = $('<i class="tree-toggle fa fa-plus-square-o" style="cursor: pointer; margin-right: 5px;" data-parent-id="' + rowData.id + '"></i>');
                                    $nameCell.prepend($icon);
                                    
                                    // 绑定点击事件
                                    $icon.on('click', function(e) {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        
                                        var parentId = $(this).data('parent-id');
                                        var isExpanded = $(this).hasClass('fa-minus-square-o');
                                        
                                        console.log('点击展开图标，parentId:', parentId, 'isExpanded:', isExpanded);
                                        
                                        if (isExpanded) {
                                            // 收缩：隐藏子分类
                                            $(this).removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
                                            $('.child-row-' + parentId).remove();
                                        } else {
                                            // 展开：显示子分类
                                            $(this).removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
                                            
                                            // 添加子分类行
                                            var children = rowData.children || [];
                                            console.log('子分类数据:', children);
                                            
                                            children.forEach(function(child, childIndex) {
                                                 var childRowHtml = '<tr class="child-row-' + parentId + '" style="background-color: #f8f9fa; border-left: 3px solid #007bff;">';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;"><input type="checkbox" name="ids" value="' + child.id + '"></td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;">' + child.id + '</td>';
                                                 childRowHtml += '<td style="vertical-align: middle; padding-left: 40px;"><span style="color: #6c757d;">└─</span> ' + child.name + '</td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;">' + (child.image ? '<img src="' + child.image + '" style="max-width: 50px; max-height: 50px;">' : '') + '</td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;">' + child.sort + '</td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;"><span class="label label-' + (child.status == 1 ? 'success' : 'danger') + '">' + (child.status == 1 ? '正常' : '隐藏') + '</span></td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;">' + Table.api.formatter.datetime(child.createtime) + '</td>';
                                                 childRowHtml += '<td class="text-center" style="vertical-align: middle;">';
                                                 childRowHtml += '<a href="javascript:;" class="btn btn-xs btn-success btn-editone" data-id="' + child.id + '"><i class="fa fa-pencil"></i> 编辑</a> ';
                                                 childRowHtml += '<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" data-id="' + child.id + '"><i class="fa fa-trash"></i> 删除</a>';
                                                 childRowHtml += '</td>';
                                                 childRowHtml += '</tr>';
                                                 
                                                 $row.after(childRowHtml);
                                             });
                                        }
                                    });
                                }
                            }
                        });
                        
                        // 绑定子分类的编辑和删除事件
                        $(document).off('click', '.btn-editone').on('click', '.btn-editone', function(e) {
                            e.preventDefault();
                            var id = $(this).data('id');
                            Fast.api.open("product/categoryedit?ids=" + id, "编辑分类", {
                                area: ['800px', '600px'],
                                callback: function(data) {
                                    table.bootstrapTable('refresh');
                                }
                            });
                        });
                        
                        $(document).off('click', '.btn-delone').on('click', '.btn-delone', function(e) {
                            e.preventDefault();
                            var id = $(this).data('id');
                            Layer.confirm("确认删除该分类？", function(index) {
                                Fast.api.ajax({
                                    url: "product/categorydel",
                                    data: {ids: id}
                                }, function(data, ret) {
                                    table.bootstrapTable('refresh');
                                    Layer.close(index);
                                });
                            });
                        });
                    }, 100);
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('分类名称'), align: 'left'},
                        {field: 'image', title: __('分类图片'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'sort', title: __('排序')},
                        {field: 'status', title: __('状态'), searchList: {"1":__('Normal'),"0":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'product/index' + location.search,
                    add_url: 'product/add',
                    edit_url: 'product/edit',
                    del_url: 'product/del',
                    multi_url: 'product/multi',
                    import_url: 'product/import',
                    table: 'product',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), width: 60},
                        {field: 'name', title: __('Name'), operate: 'LIKE', width: 200, 
                         formatter: function(value, row, index) {
                             var html = '<div style="max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + value + '">' + value + '</div>';
                             if (row.subtitle) {
                                 html += '<small class="text-muted" style="display: block; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + row.subtitle + '">' + row.subtitle + '</small>';
                             }
                             return html;
                         }},
                        {field: 'category_name', title: __('Category'), operate: 'LIKE', width: 100},
                        {field: 'merchant_name', title: __('Merchant'), operate: 'LIKE', width: 100},
                        {field: 'main_image', title: '主图片', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image, width: 80},
                        {field: 'price', title: __('Price'), operate:'BETWEEN', width: 80,
                         formatter: function(value, row, index) {
                             return '<span class="text-success">¥' + parseFloat(value).toFixed(2) + '</span>';
                         }},
                        {field: 'market_price', title: __('Market price'), operate:'BETWEEN', width: 80,
                         formatter: function(value, row, index) {
                             return value > 0 ? '<span class="text-muted">¥' + parseFloat(value).toFixed(2) + '</span>' : '-';
                         }},
                        {field: 'stock', title: __('Stock'), width: 60,
                         formatter: function(value, row, index) {
                             var color = value > 10 ? 'success' : (value > 0 ? 'warning' : 'danger');
                             return '<span class="label label-' + color + '">' + value + '</span>';
                         }},
                        {field: 'sales', title: __('Sales'), width: 60},
                        {field: 'sort', title: __('Sort'), width: 60},
                        {field: 'audit_status', title: '状态', searchList: {"0":"待审核","1":"审核通过","2":"审核拒绝"}, formatter: function(value, row, index) {
                             var auditStatusMap = {'0': {text: '待审核', class: 'warning'}, '1': {text: '审核通过', class: 'success'}, '2': {text: '审核拒绝', class: 'danger'}};
                             var auditStatus = auditStatusMap[value] || {text: '未知', class: 'default'};
                             return '<span class="label label-' + auditStatus.class + '">' + auditStatus.text + '</span>';
                         }, width: 80},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, width: 120},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function (value, row, index) {
                            var that = $.extend({}, this);
                            var table = $(that.table).clone(true);
                            
                            // 默认按钮组
                            $(table).data("operate-edit", null);
                            $(table).data("operate-del", null);
                            
                            // 添加自定义按钮
                            var buttons = [];
                            buttons.push('<a href="product/detail/ids/' + row.id + '" class="btn btn-xs btn-info btn-dialog" style="margin-right: 5px;" title="商品详情"><i class="fa fa-eye"></i> 查看详情</a>');
                            
                            // 追加默认按钮组
                            buttons = buttons.concat(Table.api.formatter.operate.call(that, value, row, index));
                            
                            return buttons.join('');
                        }, width: 150}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // 商品属性配置的复选框事件绑定
            $('#enable-equity').on('change', function() {
                if ($(this).is(':checked')) {
                    $('.equity-price-group').show();
                    $('#c-equity-price').attr('data-rule', 'required');
                } else {
                    $('.equity-price-group').hide();
                    $('#c-equity-price').removeAttr('data-rule');
                }
            });
            
            $('#enable-points').on('change', function() {
                if ($(this).is(':checked')) {
                    $('.points-price-group').show();
                    $('#c-points-price').attr('data-rule', 'required');
                } else {
                    $('.points-price-group').hide();
                    $('#c-points-price').removeAttr('data-rule');
                }
            });
            
            $('#enable-agriculture').on('change', function() {
                if ($(this).is(':checked')) {
                    $('.agriculture-price-group').show();
                    $('#c-agriculture-price').attr('data-rule', 'required');
                } else {
                    $('.agriculture-price-group').hide();
                    $('#c-agriculture-price').removeAttr('data-rule');
                }
            });
            
            Controller.api.bindevent();
        },
        categoryadd: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            // 商品属性配置的复选框事件绑定
            $('#enable-equity').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#c-equity-price').show().attr('data-rule', 'required');
                } else {
                    $('#c-equity-price').hide().removeAttr('data-rule');
                }
            });
            
            $('#enable-points').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#c-points-price').show().attr('data-rule', 'required');
                    $('#c-points').show().attr('data-rule', 'required');
                } else {
                    $('#c-points-price').hide().removeAttr('data-rule');
                    $('#c-points').hide().removeAttr('data-rule');
                }
            });
            
            $('#enable-agriculture').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#c-agriculture-price').show().attr('data-rule', 'required');
                } else {
                    $('#c-agriculture-price').hide().removeAttr('data-rule');
                }
            });
            
            Controller.api.bindevent();
        },
        categoryedit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});